PROJECT = "i2c 24c02 demo"
VERSION = "1.0.0"
local sys = require "sys"
require "Modbus"
require "ntctotemp"
require "ADS1115"
require "Mqtt"

function read()
    ADC = ADS1115.Read_ADC(0, 1)
    if ADC == nil then
        return nil
    end
    if ADC < 0 then
        abs_ADC = -ADC
    else
        abs_ADC = ADC
    end

    if abs_ADC > 2048 then

    elseif abs_ADC > 1024 then
        ADC = ADS1115.Read_ADC(0, 2)
    elseif abs_ADC > 512 then
        ADC = ADS1115.Read_ADC(0, 3)
    elseif abs_ADC > 256 then
        ADC = ADS1115.Read_ADC(0, 4)
    else
        ADC = ADS1115.Read_ADC(0, 5)
    end
    return ADC
end

function read_temp()
    temp_ADC = ADS1115.Read_ADC(7, 0)
    if temp_ADC == nil then
        return nil
    end
    PT_R = (30000 * temp_ADC) / (5000 - temp_ADC)
    return ntctotemp.temp(PT_R)+Modbus[5]
end

function jisuan()
    local pH=0
    if Modbus[8]==0 then
        pH=k1*Modbus[1]+b1
    else
        pH=k2*Modbus[1]+b2
    end
    Modbus[24]=pH+((Modbus[2]-250)*Modbus[6]/100)
 
end
k1=1/591.57
b1=7
k2=1/591.57
b2=7
--主程序
sys.taskInit(function()
    ADS1115.init()
    sys.wait(1000)
    k1=(Modbus[9]-Modbus[11])/(Modbus[10]-Modbus[12])
    b1=Modbus[9]-k1*Modbus[10]
    local xy=Modbus[13]*Modbus[14]+Modbus[15]*Modbus[16]+Modbus[17]*Modbus[18]
    local av_x=(Modbus[14]+Modbus[16]+Modbus[18])/3
    local av_y=(Modbus[13]+Modbus[15]+Modbus[17])/3

    k2=(xy-3*av_x*av_y)/(Modbus[14]*Modbus[14]+Modbus[16]*Modbus[16]+Modbus[18]*Modbus[18]-3*av_x*av_x)
    b2=av_y-k1*av_x

    while 1 do
        
        -- Modbus[1] = math.floor(read()*10)
        -- Modbus[2] = read_temp()
        Modbus[1] = 0
        Modbus[2] = 300
        jisuan()

        --print("hello world")
        --print(read_temp())
        sys.wait(1000)
    end
end)
-- 这里演示在另一个task里上报数据, 会定时上报数据,不需要就注释掉


sys.taskInit(function()
    local pub_topic = "/luatos/pub/" .. (mcu.unique_id():toHex())--定时上报的
	local qos = 1 -- QOS0不带puback, QOS1是带puback的
    while true do
        sys.wait(60000)
        Mqtt.publish(pub_topic,os.date()..","..Modbus[24], qos)
    end
end)

sys.run()
